package com.bzsg.rightsManagementSystem.config.security_config

import com.bzsg.rightsManagementSystem.pojo.PersonUser
import com.bzsg.rightsManagementSystem.service.UserService
import com.bzsg.rightsManagementSystem.util.JwtTokenUtil
import com.bzsg.rightsManagementSystem.util.result.ResultUtil
import com.bzsg.rightsManagementSystem.write
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.User
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.stereotype.Component
import java.io.IOException
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class CustomizeAuthenticationSuccessHandler : AuthenticationSuccessHandler {
    @Autowired
    lateinit var userService: UserService


    @Throws(IOException::class)
    override fun onAuthenticationSuccess(
        httpServletRequest: HttpServletRequest?, httpServletResponse: HttpServletResponse,
        authentication: Authentication?
    ) {
        //更新用户表上次登录时间、更新人、更新时间等字段
        val time = TimeZone.getTimeZone("Etc/GMT-8") //转换为中国时区
        TimeZone.setDefault(time)
        val userDetails = SecurityContextHolder.getContext().authentication.principal as User
        val userName = userDetails.username
        val user = userService.selectUserByName(userName)!!
        val token = JwtTokenUtil.createToken(user)
        user.lastLoginTime = Date()
        user.updateTime = Date()
        user.updateUser = user.id
        userService.update(user)
        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展
        //返回json数据
        httpServletResponse.contentType = "text/json;charset=utf-8"
        httpServletResponse.write(ResultUtil.success(token))
    }
}